package com.zhangye.test.api;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhangye.test.model.Admin;
import com.zhangye.test.model.SafeSession;
import com.zhangye.test.model.SmsSession;
import com.zhangye.test.service.AdminService;
import com.zhangye.test.service.SafeSessionService;
import com.zhangye.test.service.SendMsgService;
import com.zhangye.test.service.SmsSessionService;
import com.zhangye.test.util.AES;
import com.zhangye.test.util.StringUtils;


/**
 * 登录
 * 作者： 张叶
 * 创建时间：2018年6月13日  下午2:26:39
 */
@Controller
@RequestMapping("api/login")
public class LoginApi {

	@Autowired
	private SafeSessionService safeSessionService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private SmsSessionService smsSessionService;
	@Autowired
	private SendMsgService sendMsgService;

	
	/**
	 * 微信登录
	 * 作者： 张叶
	 * 创建时间：2018年8月21日  下午2:08:37
	 */
	@ResponseBody
	@RequestMapping(value = "/loginWechat",method = RequestMethod.POST)
	public ApiResult loginWechat(HttpServletRequest request,String wechatOpenId){
		ApiResult result = new ApiResult();
		if (wechatOpenId != null && !"".equals(wechatOpenId)) {
			Admin admin = safeSessionService.getCurrent(request);
			if (admin != null) {
				admin.setWechatOpenId(wechatOpenId);
				int i = adminService.updateAdmin(admin, 0);
				if(i > 0){
					result.msg.status = 0;
					result.msg.desc = "操作成功";
				} else {
					result.msg.status = 1;
					result.msg.desc = "系统错误，操作失败";
				}
			} else {
				result.msg.status = 2;
				result.msg.desc = "当前登录已失效，请重新登录";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空！";
		}
		return result;
	}

	
	/**
	 * QQ登录
	 * 作者： 张叶
	 * 创建时间：2018年8月21日  下午2:08:37
	 */
	@ResponseBody
	@RequestMapping(value = "/loginQq",method = RequestMethod.POST)
	public ApiResult loginQq(HttpServletRequest request,String qqOpenId){
		ApiResult result = new ApiResult();
		if (qqOpenId != null && !"".equals(qqOpenId)) {
			Admin admin = safeSessionService.getCurrent(request);
			if (admin != null) {
				admin.setQqOpenId(qqOpenId);
				int i = adminService.updateAdmin(admin, 0);
				if(i > 0){
					result.msg.status = 0;
					result.msg.desc = "操作成功";
				} else {
					result.msg.status = 1;
					result.msg.desc = "系统错误，操作失败";
				}
			} else {
				result.msg.status = 2;
				result.msg.desc = "当前登录已失效，请重新登录";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空！";
		}
		return result;
	}
	

	/**
	 * 微信登录绑定
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  下午1:46:01
	 */
	@ResponseBody
	@RequestMapping(value = "/wechatBinding",method = RequestMethod.POST)
	public ApiResult wechatBinding(HttpServletRequest request,
			HttpServletResponse response,String wechatOpenId,
			String telphone,String password){
		ApiResult result = new ApiResult();
		if (telphone != null && !"".equals(telphone) 
				&& password != null && !"".equals(password)
				&& wechatOpenId != null && !"".equals(wechatOpenId)) {
			Admin admin = adminService.findByTelphone(telphone);
			if (admin != null) {
				if (admin.getPassword()
						.equals(DigestUtils.md5Hex(password))) {
					String where = " and wechat_open_id = '" + wechatOpenId + "'";
					List<Admin> list = adminService.selectWhere(where);
					if(list.size() == 0){
						admin.setWechatOpenId(wechatOpenId);
						int i = adminService.updateAdmin(admin, 0);
						if(i > 0){
							String sessionId = getSessionId(request, response,
									telphone, password);
							result.msg.status = 0;
							result.msg.desc = "操作成功";
							result.data.put("sessionId", sessionId);
						} else {
							result.msg.status = 1;
							result.msg.desc = "系统错误，操作失败";
						}
					} else {
							result.msg.status = 4;
							result.msg.desc = "该账号已绑定手机号";
					}
				} else {
					result.msg.status = 5;
					result.msg.desc = "用户名或密码错误！";
				}
			} else {
				result.msg.status = 5;
				result.msg.desc = "用户名或密码错误！";
			}
		}
		return result;
	}


	/**
	 * QQ登录绑定
	 * 作者： 张叶
	 * 创建时间：2018年7月24日  下午2:38:59
	 */
	@ResponseBody
	@RequestMapping(value = "/qqBinding",method = RequestMethod.POST)
	public ApiResult qqBinding(HttpServletRequest request,
			HttpServletResponse response,String qqOpenId,
			String telphone,String password){
		ApiResult result = new ApiResult();
		if (telphone != null && !"".equals(telphone) 
				&& password != null && !"".equals(password)
				&& qqOpenId != null && !"".equals(qqOpenId)) {
			Admin admin = adminService.findByTelphone(telphone);
			if (admin != null) {
				if (admin.getPassword()
						.equals(DigestUtils.md5Hex(password))) {
					String where = " and qq_open_id = '" + qqOpenId + "'";
					List<Admin> list = adminService.selectWhere(where);
					if(list.size() == 0){
						admin.setQqOpenId(qqOpenId);
						int i = adminService.updateAdmin(admin, 0);
						if(i > 0){
							String sessionId = getSessionId(request, response,
									telphone, password);
							result.msg.status = 0;
							result.msg.desc = "操作成功";
							result.data.put("sessionId", sessionId);
						} else {
							result.msg.status = 1;
							result.msg.desc = "系统错误，操作失败";
						}
					} else {
							result.msg.status = 4;
							result.msg.desc = "该账号已绑定手机号";
					}
				} else {
					result.msg.status = 5;
					result.msg.desc = "用户名或密码错误！";
				}
			} else {
				result.msg.status = 5;
				result.msg.desc = "用户名或密码错误！";
			}
		}
		return result;
	}


	/**
	 * QQ登录
	 * 作者： 张叶
	 * 创建时间：2018年7月24日  下午2:38:59
	 */
	@ResponseBody
	@RequestMapping(value = "/qqLogin",method = RequestMethod.POST)
	public ApiResult qqLogin(HttpServletRequest request,
			HttpServletResponse response,String qqOpenId){
		ApiResult result = new ApiResult();
		String where = " and qq_open_id = '" + qqOpenId + "'";
		List<Admin> list = adminService.selectWhere(where);
		if(list.size() > 0){
			String sessionId = getSessionIdOther(request, response,
					list.get(0).getTelphone(),list.get(0).getPassword());
			result.msg.status = 0;
			result.msg.desc = "登录成功";
			result.data.put("sessionId", sessionId);
		} else {
			result.msg.status = 1;
			result.msg.desc = "当前QQ未绑定账号，请先绑定";
		}
		return result;
	}


	/**
	 * 微信登录
	 * 作者： 张叶
	 * 创建时间：2018年7月24日  下午2:38:59
	 */
	@ResponseBody
	@RequestMapping(value = "/wechatLogin",method = RequestMethod.POST)
	public ApiResult wechatLogin(HttpServletRequest request,
			HttpServletResponse response,String wechatOpenId){
		ApiResult result = new ApiResult();
		String where = " and wechat_open_id = '" + wechatOpenId + "'";
		List<Admin> list = adminService.selectWhere(where);
		if(list.size() > 0){
			String sessionId = getSessionIdOther(request, response,
					list.get(0).getTelphone(),list.get(0).getPassword());
			result.msg.status = 0;
			result.msg.desc = "登录成功";
			result.data.put("sessionId", sessionId);
		} else {
			result.msg.status = 1;
			result.msg.desc = "当前微信未绑定账号，请先绑定";
		}
		return result;
	}
	
	
	/**
	 * 登录 
	 *  “type”:android/ios
	 * 作者：张叶 
	 * 创建时间：2016年8月12日 上午11:09:41
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ApiResult login(HttpServletRequest request,
			HttpServletResponse response, String datas,String type) {
		ApiResult result = new ApiResult();
		result.msg.status = 1;
		result.msg.desc = "登录失败";
		String reqParam = request.getParameter("datas");
		if(type != null && !"".equals(type)){
			if(type.equals("android")){
				byte[] aes = AES.decrypt(StringUtils.parseHexStr2Byte(reqParam));
				try {
					reqParam = new String(aes, "utf-8");
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			}
			JSONObject jasonObject = JSONObject.fromObject(reqParam);
			String telphone = (String) jasonObject.get("telphone");
			String password = (String) jasonObject.get("password");
			if (telphone != null && !telphone.equals("") && password != null
					&& !password.equals("")) {
				Admin admin = adminService.findByTelphone(telphone);
				if (admin != null) {
					if (admin.getPassword()
							.equals(DigestUtils.md5Hex(password))) {
						String sessionId = getSessionId(request, response,
								telphone, password);
						result.msg.status = 0;
						result.msg.desc = "登录成功";
						result.data.put("sessionId", sessionId);
					} else {
						result.msg.status = -2;
						result.msg.desc = "用户名或密码错误！";
					}
				} else {
					result.msg.status = -2;
					result.msg.desc = "用户名或密码错误！";
				}
			}
		} else {
			result.msg.status = 1;
			result.msg.desc = "参数不能为空！";
		}
		return result;
	}

	
	/**
	 * 忘记密码
	 * 作者： 张叶
	 * 创建时间：2018年6月28日  下午5:00:24
	 */
	@ResponseBody
	@RequestMapping(value = "/forgetPassword", method = RequestMethod.POST)
	public ApiResult forgetPassword(HttpServletRequest request,
			HttpServletResponse response, String datas,String type) {
		ApiResult result = new ApiResult();
		result.msg.status = 1;
		result.msg.desc = "修改失败";
		String reqParam = request.getParameter("datas");
		if(type != null && !"".equals(type)){
			if(type.equals("android")){
				byte[] aes = AES.decrypt(StringUtils.parseHexStr2Byte(reqParam));
				try {
					reqParam = new String(aes, "utf-8");
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			}
			JSONObject jasonObject = JSONObject.fromObject(reqParam);
			String telphone = (String) jasonObject.get("telphone");
			String password = (String) jasonObject.get("password");
			String smsCode = (String) jasonObject.get("smsCode");
			
			SmsSession ss = smsSessionService.findBySessionId(telphone);
			if(ss != null && !"".equals(ss)){

//				try {
//					int reInt = smsService.verifySMSCode(ss.getSessionId(), smsCode);
//					if (reInt == 0) {
					if(smsCode.equals(ss.getSessionId())){
						Admin admin = adminService.findByTelphone(telphone);
						if (admin != null && !"".equals(admin)) {
							admin.setPassword(DigestUtils.md5Hex(password));
							int count = adminService.updateAdmin(admin, 0);
							if (count > 0) {
								result.msg.status = 0;
								result.msg.desc = "修改成功！";
							} else {
								result.msg.status = 1;
								result.msg.desc = "修改失败！";
							}
						} else {
							result.msg.status = 2;
							result.msg.desc = "当前用户未注册";
						}
					} else {
						result.msg.status = 3;
						result.msg.desc = "验证码输入错误！";
					}
//				} catch (Exception e) {
//					result.msg.status = 5;
//					result.msg.desc = "短信验证码验证失败";
//				}
			}else{
				result.msg.status = 3;
				result.msg.desc = "验证码输入错误！";
			}
		} else {
			result.msg.status = 4;
			result.msg.desc = "参数不能为空！";
		}
		return result;
	}

	
	/**
	 * 修改密码 
	 * 作者：张叶 
	 * 创建时间：2016年8月15日 上午10:55:32
	 */
	@ResponseBody
	@RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
	public ApiResult modifyPassword(HttpServletRequest request, String datas,String type) {
		ApiResult result = new ApiResult();
		result.msg.status = 1;
		result.msg.desc = "修改失败";
		String reqParam = request.getParameter("datas");
		if(type != null && !"".equals(type)){
			if(type.equals("android")){
				byte[] aes = AES.decrypt(StringUtils.parseHexStr2Byte(reqParam));
				try {
					reqParam = new String(aes, "utf-8");
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			}
			JSONObject jasonObject = JSONObject.fromObject(reqParam);
			String oldPwd = (String) jasonObject.get("oldPwd");
			String newPwd = (String) jasonObject.get("newPwd");

			Admin existAdmin = safeSessionService.getCurrent(request);
			if (existAdmin != null) {
				if (existAdmin.getPassword().equals(DigestUtils.md5Hex(oldPwd))) {// 输入旧密码一致
					existAdmin.setPassword(DigestUtils.md5Hex(newPwd));
					int count = adminService.updateAdmin(existAdmin, 0);
					if (count > 0) {
						result.msg.status = 0;
						result.msg.desc = "修改成功！";
					} else {
						result.msg.status = 1;
						result.msg.desc = "修改失败！";
					}
				} else {// 输入旧密码不一致
					result.msg.status = 3;
					result.msg.desc = "旧密码不正确，请重新输入！";
				}
			} else {
				result.msg.status = 2;
				result.msg.desc = "当前登录已失效，请重新登录";
			}
		} else {// 输入旧密码不一致
			result.msg.status = 4;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}
	
	
	/**
	 * 退出登录 
	 * 作者： 张叶 
	 * 创建时间：2018年6月13日 上午11:34:44
	 */
	@ResponseBody
	@RequestMapping(value = "/signOut", method = RequestMethod.POST)
	public ApiResult signOut(String sessionId, HttpServletRequest request) {
		ApiResult result = new ApiResult();
		result.msg.status = 0;
		result.msg.desc = "退出成功";
		HttpSession session = request.getSession();
		session.removeAttribute("sessionId");
		session.removeAttribute("password");
		session.removeAttribute("username");
		return result;
	}
	

	/**
	 * 快速登录 
	 * 作者： 张叶 
	 * 创建时间：2018年6月13日 上午11:34:30
	 */
	@ResponseBody
	@RequestMapping(value = "/quick", method = RequestMethod.POST)
	public ApiResult quickLogin(String sessionId) {
		ApiResult result = new ApiResult();
		result.msg.desc = "当前登录已失效，请重新登录";
		result.msg.status = 2;
		SafeSession ss = safeSessionService.findBySessionId(sessionId);
		if (ss != null) {
			String telphone = ss.getAccountno();
			Admin m = adminService.findByTelphone(telphone);
			if (m != null) {
				result.msg.status = 0;
				result.msg.desc = "登录成功";
			} else {
				safeSessionService.deleted(ss.getAccountno());
				result.msg.desc = "当前登录已失效，请重新登录";
				result.msg.status = 2;
			}
		} else {
			result.msg.desc = "当前登录已失效，请重新登录";
			result.msg.status = 2;
		}
		return result;
	}

	
	/**
	 * 获取SessionId 
	 * 作者： 张叶 
	 * 创建时间：2018年6月13日 上午11:37:32
	 */
	private String getSessionId(HttpServletRequest request,
			HttpServletResponse response, String telphone, String password) {
		String sessionId;
		SafeSession safeSession = safeSessionService.findByAccountAndPassword(
				telphone, DigestUtils.md5Hex(password));// 判断是否登录过
		if (safeSession != null) {
			sessionId = DigestUtils.md5Hex(telphone) + "_"
					+ UUID.randomUUID().toString() + "_"
					+ DigestUtils.md5Hex(password);// 用户名+uuid+密码
			HttpSession session = request.getSession();
			Cookie cookie = new Cookie("ar_token", session.getId());
			cookie.setMaxAge(30 * 24 * 60 * 60);// 有效时长30天
			response.addCookie(cookie);
			safeSession.setSessionid(sessionId);
			safeSession.setCreatedate(new Date());
			safeSessionService.update(safeSession);
			session.setAttribute("sessionId", sessionId);
			session.setAttribute("password", safeSession.getPassword());
			session.setAttribute("telphone", telphone);
		} else {
			sessionId = DigestUtils.md5Hex(telphone) + "_"
					+ UUID.randomUUID().toString() + "_"
					+ DigestUtils.md5Hex(password);// 用户名+uuid+密码
			HttpSession session = request.getSession();
			Cookie cookie = new Cookie("ar_token", session.getId());
			cookie.setMaxAge(30 * 24 * 60 * 60);
			response.addCookie(cookie);
			session.setAttribute("sessionId", sessionId);
			session.setAttribute("password", DigestUtils.md5Hex(password));
			session.setAttribute("telphone", telphone);
			SafeSession ss = new SafeSession();
			ss.setAccountno(telphone);
			ss.setCreatedate(new Date());
			ss.setSessionid(sessionId);
			ss.setPassword(DigestUtils.md5Hex(password));
			safeSessionService.deleted(telphone);
			safeSessionService.insert(ss);
		}
		return sessionId;
	}
	
	/**
	 * 获取SessionId 
	 * 作者： 张叶 
	 * 创建时间：2018年6月13日 上午11:37:32
	 */
	private String getSessionIdOther(HttpServletRequest request,
			HttpServletResponse response, String telphone, String password) {
		String sessionId;
		SafeSession safeSession = safeSessionService.findByAccountAndPassword(
				telphone, password);// 判断是否登录过
		if (safeSession != null) {
			sessionId = DigestUtils.md5Hex(telphone) + "_"
					+ UUID.randomUUID().toString() + "_"
					+ password;// 用户名+uuid+密码
			HttpSession session = request.getSession();
			Cookie cookie = new Cookie("ar_token", session.getId());
			cookie.setMaxAge(30 * 24 * 60 * 60);// 有效时长30天
			response.addCookie(cookie);
			safeSession.setSessionid(sessionId);
			safeSession.setCreatedate(new Date());
			safeSessionService.update(safeSession);
			session.setAttribute("sessionId", sessionId);
			session.setAttribute("password", safeSession.getPassword());
			session.setAttribute("telphone", telphone);
		} else {
			sessionId = DigestUtils.md5Hex(telphone) + "_"
					+ UUID.randomUUID().toString() + "_"
					+ password;// 用户名+uuid+密码
			HttpSession session = request.getSession();
			Cookie cookie = new Cookie("ar_token", session.getId());
			cookie.setMaxAge(30 * 24 * 60 * 60);
			response.addCookie(cookie);
			session.setAttribute("sessionId", sessionId);
			session.setAttribute("password", password);
			session.setAttribute("telphone", telphone);
			SafeSession ss = new SafeSession();
			ss.setAccountno(telphone);
			ss.setCreatedate(new Date());
			ss.setSessionid(sessionId);
			ss.setPassword(password);
			safeSessionService.deleted(telphone);
			safeSessionService.insert(ss);
		}
		return sessionId;
	}
	
}
